const path = require('path')
const resolve = (dir) => path.join(__dirname, dir)
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i
const isProd = process.env.NODE_ENV === 'production'

// cdn或排除不打包的模块
const assetsCDN = {
  externals: {}
}

module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? '/vue-spline' : '/',
  lintOnSave: true,
  productionSourceMap: false,

  // 调整内部的 webpack 配置
  chainWebpack: (config) => {
    config.resolve.alias.set('@', resolve('src')).set('api', resolve('src/api'))
    config.output.chunkFilename(`js/[name].[chunkhash:8].js`)
    config.module.rule('svg').exclude.add(resolve('src/assets/icons')).end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
  },

  configureWebpack: (config) => {
    if (isProd) {
      config.plugins.push(
        new CompressionWebpackPlugin({
          test: productionGzipExtensions,
          threshold: 10240,
          minRatio: 0.8
        })
      )
      // 替换cdn或排除打包模块
      config.externals = assetsCDN.externals || {}
    }
  },

  css: {
    sourceMap: !isProd,
    loaderOptions: {
      less: {
        lessOptions: {
          javascriptEnabled: true,
          modifyVars: {
            hack: `true;
            @import "${resolve('src/assets/styles/variables/index.less')}";`
          }
        }
      }
    }
  },

  devServer: {
    port: 8702,
    proxy: {
      '/api-v1': {
        target: ' http://0.0.0.0:9002',
        changeOrigin: true,
        pathRewrite: {
          '^/api-v1': '/'
        }
      }
    }
  }
}
